#!/bin/sh

[ "$RELEASEDIR" ] || RELEASEDIR=../Release
[ "$REACTOR_PATH" ] || REACTOR_PATH=..
[ "$REACTOR" ] || REACTOR=$RELEASEDIR/bin/reactor

export REACTOR_PATH REACTOR

error(){
	err=$1
	shift
	echo $*
	exit $err
}

SAVE=false
[ "$1" -a "$1" == "--remove" ] && REMOVE=true && shift
[ "$1" -a "$1" == "--save" ] && SAVE=true && shift
[ "$1" -a -f "$1" ] || error 1 "Syntax: $0 [--remove|--save] <test-file.R>"
F=$1 && shift

unset ARGSFILE OUTFILE INFILE ERRFILE RESFILE
[ -f "$F.args" ] && ARGSFILE='`$F.args`'
[ -f "$F.out" ] && OUTFILE="$F.out"
[ -f "$F.in" ] && INFILE="< $F.in"
[ -f "$F.err" ] && ERRFILE="$F.err"
[ -f "$F.res" ] && RESFILE="$F.res"

[ "$REMOVE" ] && rm -f $ARGSFILE $OUTFILE $ERRFILE $RESFILE && unset ARGSFILE OUTFILE ERRFILE RESFILE

TMPNAM="mktemp -t reactor"

TOUT=`$TMPNAM`
TERR=`$TMPNAM`

echo "$REACTOR $F $ARGS > $TOUT 2> $TERR $INFILE"
$REACTOR $F $ARGS 2> $TERR $INFILE | tee $TOUT 
RES="$?"

R=0
if [ "$RESFILE" ] ; then
	failure_res() {
		echo "----- RESULT -----"
		echo "FAILURE ($1 != $2)"
		R=$((R + 1))
	}
	[ "$RES" == `cat $RESFILE` ] || failure_res $RES `cat $RESFILE`
fi
failure_diff() {
	echo "----- $1 -----"
	cat $2
	R=$((R + $3))
}

if [ "$OUTFILE" ] ; then
	OO=`$TMPNAM`
	diff -u $TOUT $OUTFILE > $OO || failure_diff STDOUT $OO 10
	rm $OO
fi

if [ "$ERRFILE" ] ; then
	OO=`$TMPNAM`
	diff -u $TERR $ERRFILE > $OO || failure_diff STDERR $OO 100
	rm $OO
fi


if $SAVE ; then
	echo "Result of '$F' saved"
	echo $* > "$F.args"
	echo $RES > "$F.res"
	cat $TOUT > "$F.out"
	cat $TERR > "$F.err"
fi
rm $TOUT $TERR

exit $R
